﻿$(document).ready(function () {


    //Next textbox focus
    $(function () {
        var isPostBackObject = document.getElementById('isPostBack');
        if (isPostBackObject == null) {
            //$(':input:text:visible:not(disabled):not([readonly]):not(.NormalTextBox):first').focus();
            try {
                $('form').find('input[type=text],textarea,select').filter(':visible:not(disabled):not([readonly]):not(.NormalTextBox):first').focus();
            } catch (err) {
                FocusFirst();
                NextFocus();
            }
        }
        NextFocus();
    });

});

function NextFocus() {
    var $inp = $(':input:enabled:visible:not(disabled):not([readonly]):not(.NormalTextBox)');
    $inp.bind('keydown', function (e) {
        //var key = (e.keyCode ? e.keyCode : e.charCode);
        var key = e.which;
        if (key == 13) {
            tname = $(this).attr('type');
            if (tname != 'textarea') {
                iname = $(this).val();
                if (iname != 'เพิ่มรายละเอียด') {
                    e.preventDefault();
                    var nxtIdx = $inp.index(this) + 1;
                    $inp.eq(nxtIdx).focus();
                }
            }
        }
    });
}

function FocusFirst() {
    var bFound = false;
    //for each form
    for (f = 0; f < document.forms.length; f++) {
        //for each form element
        for (i = 0; i < document.forms[f].length; i++) {
            el = document.forms[f][i]
            if (el.disabled != true) {
                if (el.type != undefined) {
                    switch (el.type.toLowerCase()) {
                        case "text": el.focus(); bFound = true; break;
                        case "textarea": el.focus(); bFound = true; break;
                        case "checkbox": el.focus(); bFound = true; break;
                        case "radio": el.focus(); bFound = true; break;
                        case "file": el.focus(); bFound = true; break;
                        case "password": el.focus(); bFound = true; break;
                        case "select-one": el.focus(); bFound = true; break;
                        case "select-multiple": el.focus(); bFound = true; break;
                    } // switch el.type
                } //if (el.type != undefined) 
            } //if (el.disabled != true)
            if (bFound == true) break;
        } //for each form element
        if (bFound == true) break;
    } //for each form
}
